package com.future.common.config;

import java.util.Set;

import org.reflections.Reflections;

import com.future.common.annotation.ControllerMapping;
import com.jfinal.config.Routes;
import com.jfinal.kit.StrKit;

import lombok.extern.slf4j.Slf4j;

/**
 * 扫描controller并自动注册为route
 * 
 * @author Leon.Zhang
 *
 */
@Slf4j
public class ControllerScan extends Routes {

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public void config() {
		Reflections reflections = new Reflections("com.future.controller");		
		Set<Class<?>> controllerClasses = reflections.getTypesAnnotatedWith(ControllerMapping.class);
		for (Class controller : controllerClasses) {
			ControllerMapping controllerBind = (ControllerMapping) controller.getAnnotation(ControllerMapping.class);
			String[] controllerKeys = controllerBind.value();
			String viewPath = controllerBind.viewPath();
			for (String controllerKey : controllerKeys) {
				controllerKey = controllerKey.trim();
				if (controllerKey.equals("")) {
					if (log.isErrorEnabled())
						log.error(controller.getName() + "注解错误，映射路径为空");
					throw new RuntimeException(controller.getName() + "注解错误，映射路径为空");
				}
				// 注册映射
				if (StrKit.notBlank(viewPath)) {
					add(controllerKey, controller, viewPath);
				} else {
					add(controllerKey, controller);
				}
				if (log.isInfoEnabled())
					log.info("Controller注册： controller = " + controller + ", " + controllerKey);
			}
		}

	}

}
